package com.wangdong.wdutils.utils;

/**
 * Created by luyz on 2018/1/31.
 * url encoder
 */

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 类UrlEncoderUtils.java的实现描述：
 *
 * @author luyz 2016年4月23日 下午4:52:15
 */
public class DLUrlEncoderUtils {

    /**
     * 解码
     * @param str
     * @return
     */
    public static String utf8Decode(String str){

        if (DLStringUtil.notEmpty(str)) {
            try {
                if (isUtf8Url(str)) {
                    return URLDecoder.decode(str, "UTF-8");
                }
                return str;
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /**
     * 编码
     * @param str
     * @return
     */
    public static String utf8Encode(String str) {
        if (DLStringUtil.notEmpty(str)) {
            try {
                if (!isUtf8Url(str)){
                    return URLEncoder.encode(str, "UTF-8");
                }
                return str;

            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /**
     * 编码是否有效
     * @param text String
     * @return boolean
     */
    private static boolean Utf8codeCheck(String text){
        String sign = "";
        if (text.startsWith("%e")) {
            for (int i = 0, p = 0; p != -1; i++) {
                p = text.indexOf("%", p);
                if (p != -1) {
                    p++;
                }
                sign += p;
            }
        }
        return sign.equals("147-1");
    }
    /**
     * 判断是否Utf8Url编码
     * @param text String
     * @return boolean
     */
    public static boolean isUtf8Url(String text) {
        text = text.toLowerCase();
        int p = text.indexOf("%");
        if (p != -1 && text.length() - p > 9) {
            text = text.substring(p, p + 9);
        }
        return Utf8codeCheck(text);
    }

}
